package com.wuyou.securitydemo.component;

import cn.hutool.core.util.StrUtil;
import com.wuyou.sso.common.contant.CacheKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * ValidateComponent
 *
 * @Date 2025/4/10 15:48
 * @Author 无忧
 */
@Component
@Slf4j
public class ValidateComponent {


    @Autowired
    private RedisTemplate redisTemplate;


    public void validate(String randomStr, String code){
        String key = CacheKey.DEFAULT_CODE + randomStr;
        try {
            if (StringUtils.isBlank(randomStr) || StringUtils.isBlank(code)) {
                throw new IllegalArgumentException("验证码不合法");
            }
            if (!redisTemplate.hasKey(key)) {
                throw new IllegalArgumentException("验证码不合法");
            }
            Object cacheCode = redisTemplate.opsForValue().get(key);
            if (cacheCode == null) {
                throw new IllegalArgumentException("验证码不合法");
            }
            if (!StrUtil.equals((String)cacheCode, code)) {
                throw new IllegalArgumentException("验证码错误");
            }
        } finally {
            redisTemplate.delete(key);
        }

    }

}
